package nl.virtueleboekenkast.service

import nl.virtueleboekenkast.domain.{Auteur, Boek}
import scala.io.Source
import collection.mutable.ArrayBuffer
import java.text.SimpleDateFormat
import java.util.Date

class BoekenRepositoryCSV {

  private val formatter = new SimpleDateFormat("dd-MM-yyyy")

  /**
   * FORMAT: comma separated
   *
   * 0.  titel          string  mapped
   * 1.  auteur         string  mapped
   * 2.  genre          string
   * 3.  paperback      integer
   * 4.  volgnummer     integer
   * 5.  naam-van-serie string
   * 6.  publishDatum   date
   * 7.  aankoopDatum   date    mapped
   * 8.  isbn           string  mapped
   * 9.  commentaar     string  mapped
   */
  def parse(filename: String): Array[Boek] = {
    val boeken = ArrayBuffer[Boek]()
    Source.fromFile(filename).getLines().map(_.split("',")).foreach(parts => {
      boeken += mapBoek(parts)
    })
    boeken.toArray
  }

  protected def mapBoek(incoming: Array[String]): Boek = {
    val parts = incoming.map(sanitize(_))
    val titels = parts(0).split("\\n").map({_.trim})
    val naamAuteur = parts(1)
    val aankoopDatum = parts(7)
    val isbn = parts(8)
    val commentaar = parts(9)
    new Boek(titels, new Auteur(naamAuteur), isbn, mapDate(aankoopDatum), commentaar)
  }

  protected def mapDate(incoming: String): Date = {
    var result: Date = null
    if (!incoming.isEmpty)
      result = formatter.parse(incoming)
    result
  }

  protected def sanitize(incoming: String): String = {
    var subject = incoming
    if (subject.startsWith("'"))
      subject = subject.substring(1, subject.length)
    if (subject.endsWith("'"))
      subject = subject.substring(0, subject.length - 1)
    subject.trim()
  }
}
